package com.blb.productservice.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blb.common.entity.Product;
import com.blb.common.entity.ResponseResult;
import com.blb.productservice.config.ProductControllerBlockHandler;
import com.blb.productservice.config.ProductControllerFallback;
import com.blb.productservice.service.ProductService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Random;

@Slf4j
@RefreshScope
@RestController
public class ProductController {

    @Value("${server.port}")
    private Integer port;

    @Value("${spring.datasource.url}")
    private String url;

    @GetMapping("product-service-config")
    public String getProductServiceConfig(){
        return url;
    }

    @SentinelResource(value = "hello",
            blockHandlerClass = ProductControllerBlockHandler.class,blockHandler = "helloBlockHandler",
            fallbackClass = ProductControllerFallback.class,fallback = "helloFallback")
    @GetMapping("hello")
    public String hello(){
        if(new Random().nextInt(2) == 0){
            throw new RuntimeException("Error!!!");
        }
        System.out.println(LocalDateTime.now());
        return "hello" + LocalDateTime.now();
    }

    @GetMapping("world")
    public String world(){
        return "world";
    }

    @Autowired
    private ProductService productService;

    private long start;

    //设置方法调用熔断，指定降级方法，返回兜底数据
    // System.currentTimeMillis()

//    @HystrixCommand(fallbackMethod = "getProductByIdFallback")
    @GetMapping("product/{id}")
    public Product getProductById(@PathVariable Long id){
        start = System.currentTimeMillis();
        try {
            Thread.sleep(new Random().nextInt(4000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        if(id == 1){
//            throw new RuntimeException("Error");
//        }
        Product product = productService.getById(id);
        product.setName(product.getName() + "-from:" + port);
        System.out.println("查询了" + port + "服务器" + product);
        return product;
    }

//    //查询商品降级方法
//    public Product getProductByIdFallback(Long id){
//        long end = System.currentTimeMillis();
//        System.out.println("熔断时间：" + (end - start));
//        //返回兜底数据
//        Product product = new Product();
//        product.setId(id);
//        product.setName("兜底商品数据");
//        return product;
//    }

    @GetMapping("product-page")
    public ResponseResult<Page<Product>> getProductPage(@RequestParam(required = false,defaultValue = "1") Long current,
                                                        @RequestParam(required = false,defaultValue = "10") Long size){
        Page<Product> page = productService.page(new Page<>(current, size));
        return ResponseResult.ok(page);
    }

    @PostMapping("product")
    public ResponseResult<String> addProduct(@RequestBody Product product){
        productService.save(product);
        return ResponseResult.ok("ok");
    }

    @PutMapping("product")
    public ResponseResult<String> updateProduct(@RequestBody Product product){
        productService.updateById(product);
        return ResponseResult.ok("ok");
    }

    @DeleteMapping("product/{id}")
    public ResponseResult<String> removeProduct(@PathVariable Long id){
        productService.removeById(id);
        return ResponseResult.ok("ok");
    }
}
